// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const { action, data, callerOpenId } = event; // 增加 callerOpenId
  
  // 检查参数有效性
  if (!action) {
    return {
      success: false,
      message: '缺少操作类型(action)'
    }
  }
  
  // 决定使用哪个 openid 进行权限检查
  let effectiveOpenId = callerOpenId; // 优先使用调用方传递的 OPENID
  if (!effectiveOpenId) {
    // 如果调用方没有传递，则尝试使用当前云函数的调用者 OPENID (适用于客户端直接调用)
    if (wxContext && wxContext.OPENID) {
      effectiveOpenId = wxContext.OPENID;
    } else {
      return {
        success: false,
        message: '无法确定用户身份进行权限检查 '
      };
    }
  } 
  if (typeof effectiveOpenId !== 'string' || effectiveOpenId.length === 0) {
    return {
      success: false,
      message: `权限检查失败：无效的用户ID (ID: ${effectiveOpenId}, 类型: ${typeof effectiveOpenId})。`
    };
  }
  
  // 检查用户存在性
  let userRole = 'unknown';
  try {
    const userResult = await db.collection('users').where({
      openid: effectiveOpenId
    }).get();
    
    console.log('查询到的用户信息:', userResult);
    
    if (!userResult.data || userResult.data.length === 0) {
      console.log('用户不存在，但对于查询操作将允许继续');
      if (action !== 'get' && action !== 'list') {
        return {
          success: false,
          message: '用户不存在 (ID: ' + effectiveOpenId + ')'
        }
      }
    } else {
      userRole = userResult.data[0].role;
    }
  } catch (error) {
    console.error('检查用户失败:', error);
    // 对于查询操作，即使检查失败也允许继续
    if (action !== 'get' && action !== 'list') {
      return {
        success: false,
        message: '检查用户失败: ' + (error.message || '未知错误')
      }
    }
  }
  
  // 对于修改操作，检查权限
  if (action !== 'get' && action !== 'list') {
    if (userRole !== '宿管' && userRole !== '管理员') {
      return {
        success: false,
        message: '无操作权限 (用户角色: ' + userRole + ')'
      }
    }
  }
  
  try {
    switch (action) {
      // 创建新宿舍
      case 'create':
        return await createDorm(data, effectiveOpenId) // 可能需要传递 openid
      
      // 更新宿舍信息
      case 'update':
        return await updateDorm(data, effectiveOpenId) // 可能需要传递 openid
      
      // 删除宿舍
      case 'delete':
        return await deleteDorm(data.dormId, effectiveOpenId) // 可能需要传递 openid
      
      // 获取宿舍列表
      case 'list':
        return await listDorms(data)
      
      // 获取单个宿舍详情
      case 'get':
        return await getDorm(data.dormId)
      
      // 批量创建宿舍
      case 'batchCreate':
        return await batchCreateDorms(data.dorms, effectiveOpenId) // 可能需要传递 openid
      
      // 重置评分
      case 'resetScore':
        return await resetDormScore(data.dormId, data.score, effectiveOpenId) // 可能需要传递 openid
        
      default:
        return {
          success: false,
          message: '未知操作'
        }
    }
  } catch (error) {
    console.error('管理宿舍数据操作失败', error)
    return {
      success: false,
      error: error
    }
  }
}

// 创建新宿舍
async function createDorm(dormData, openid) {
  // 检查宿舍是否已存在
  const exist = await db.collection('dorms').where({
    building: dormData.building,
    roomNo: dormData.roomNo
  }).count()
  
  if (exist.total > 0) {
    return {
      success: false,
      message: '该宿舍已存在'
    }
  }
  
  // 创建新宿舍
  const now = new Date()
  const newDorm = {
    building: dormData.building,
    roomNo: dormData.roomNo,
    members: dormData.members || [],
    monitorId: dormData.monitorId || '',
    currentScore: dormData.currentScore || 80, // 默认初始分数
    scoreHistory: [],
    images: dormData.images || [],
    medals: getInitialMedals(dormData.currentScore || 80),
    createTime: now,
    updateTime: now
  }
  
  const result = await db.collection('dorms').add({
    data: newDorm
  })
  
  return {
    success: true,
    dormId: result._id,
    message: '创建宿舍成功'
  }
}

// 更新宿舍信息
async function updateDorm(dormData, openid) {
  if (!dormData._id) {
    return {
      success: false,
      message: '缺少宿舍ID'
    }
  }
  
  // 获取当前宿舍数据以便进行比较
  let currentDorm;
  try {
    currentDorm = await db.collection('dorms').doc(dormData._id).get();
    console.log('当前宿舍数据:', currentDorm);
  } catch (err) {
    console.error('获取宿舍数据失败:', err);
    return {
      success: false,
      message: '获取宿舍数据失败: ' + (err.message || '未知错误')
    }
  }
  
  if (!currentDorm.data) {
    return {
      success: false,
      message: '宿舍不存在'
    }
  }
  
  // 更新字段
  const updateData = {}
  
  // 只更新提供的字段
  if (dormData.hasOwnProperty('building')) updateData.building = dormData.building
  if (dormData.hasOwnProperty('roomNo')) updateData.roomNo = dormData.roomNo
  if (dormData.hasOwnProperty('members')) updateData.members = dormData.members
  if (dormData.hasOwnProperty('monitorId')) updateData.monitorId = dormData.monitorId
  if (dormData.hasOwnProperty('images')) updateData.images = dormData.images
  
  // 特殊处理分数和勋章
  if (dormData.hasOwnProperty('currentScore')) {
    updateData.currentScore = dormData.currentScore
    
    // 根据分数自动处理勋章
    const oldMedals = currentDorm.data.medals || [];
    
    if (dormData.currentScore >= 90) {
      // 分数≥90，添加优秀宿舍勋章
      if (!oldMedals.includes('优秀宿舍')) {
        updateData.medals = [...oldMedals, '优秀宿舍'];
      } else {
        updateData.medals = oldMedals;
      }
    } else if (dormData.currentScore < 60) {
      // 分数<60，清空所有勋章
      updateData.medals = [];
    } else {
      // 分数在60-90之间，移除优秀宿舍勋章但保留其他勋章
      updateData.medals = oldMedals.filter(m => m !== '优秀宿舍');
    }
    
    // 如果显式指定了medals，则优先使用指定的值
    if (dormData.hasOwnProperty('medals')) {
      updateData.medals = dormData.medals;
    }
    
    // 添加分数记录到历史
    if (!dormData.skipHistory) {
      const historyItem = {
        date: new Date(),
        score: dormData.currentScore,
        checkerId: dormData.checkerId || 'system',
        checkerName: dormData.checkerName || '系统更新'
      };
      
      if (currentDorm.data.scoreHistory && Array.isArray(currentDorm.data.scoreHistory)) {
        updateData.scoreHistory = _.push([historyItem]);
      } else {
        updateData.scoreHistory = [historyItem];
      }
    }
  }
  
  updateData.updateTime = new Date()
  
  // 执行更新
  try {
    await db.collection('dorms').doc(dormData._id).update({
      data: updateData
    });
    console.log('宿舍更新成功:', updateData);
  } catch (updateErr) {
    console.error('更新宿舍数据失败:', updateErr);
    return {
      success: false,
      message: '更新宿舍数据失败: ' + (updateErr.message || '未知错误')
    }
  }
  
  // 如果分数有变化，检查是否需要相应调整任务状态
  if (dormData.hasOwnProperty('currentScore') && dormData.currentScore !== currentDorm.data.currentScore) {
    if (dormData.currentScore < 60) {
      console.log('[manageDorms] 分数低于60，任务创建/更新将由 cleanupAndResetTasks 处理。');
    } else if (dormData.currentScore >= 60 && currentDorm.data.currentScore < 60) {
      // 从不及格变为及格，可以自动关闭整改任务
      try {
        await db.collection('tasks').where({
          dormId: dormData._id,
          status: _.in(['待整改', '已提交'])
        }).update({
          data: {
            status: '已整改',
            updateTime: new Date(),
            completedScore: dormData.currentScore,
            feedback: {
              content: `宿舍环境已改善，当前分数: ${dormData.currentScore}分`,
              submitTime: new Date(),
              submitterId: dormData.checkerId || 'system',
              submitterName: dormData.checkerName || '系统更新'
            }
          }
        });
      } catch (taskUpdateErr) {
        console.error('更新整改任务状态失败:', taskUpdateErr);
        // 任务处理失败不影响主流程
      }
    }
  }
  
  return {
    success: true,
    message: '更新宿舍成功'
  }
}

// 删除宿舍
async function deleteDorm(dormId, openid) {
  // 首先检查是否有关联的任务
  const tasks = await db.collection('tasks').where({
    dormId: dormId
  }).count()
  
  if (tasks.total > 0) {
    // 有关联任务，执行关联删除
    await db.collection('tasks').where({
      dormId: dormId
    }).remove()
  }
  
  // 检查是否有检查记录
  const checks = await db.collection('checks').where({
    dormId: dormId
  }).count()
  
  if (checks.total > 0) {
    // 有检查记录，执行关联删除
    await db.collection('checks').where({
      dormId: dormId
    }).remove()
  }
  
  // 删除宿舍
  await db.collection('dorms').doc(dormId).remove()
  
  return {
    success: true,
    message: '删除宿舍及关联数据成功'
  }
}

// 获取宿舍列表
async function listDorms(params = {}) {
  let query = db.collection('dorms')
  
  // 按楼栋筛选
  if (params.building) {
    query = query.where({
      building: params.building
    })
  }
  
  // 按房间号筛选
  if (params.roomNo) {
    query = query.where({
      roomNo: db.RegExp({
        regexp: params.roomNo,
        options: 'i'
      })
    })
  }
  
  // 按分数范围筛选 (添加默认值防止 undefined)
  if (params.minScore !== undefined && params.minScore !== null) {
    query = query.where({
      currentScore: _.gte(params.minScore)
    })
  }
  
  if (params.maxScore !== undefined && params.maxScore !== null) {
    query = query.where({
      currentScore: _.lte(params.maxScore)
    })
  }
  
  // 按勋章筛选
  if (params.medal) {
    query = query.where({
      medals: db.RegExp({
        regexp: params.medal,
        options: 'i'
      })
    })
  }
  
  // 设置排序
  if (params.orderBy) {
    const order = params.orderDesc ? 'desc' : 'asc'
    query = query.orderBy(params.orderBy, order)
  } else {
    // 默认按分数降序
    query = query.orderBy('currentScore', 'desc')
  }
  
  // 分页
  const pageSize = params.pageSize || 10
  const page = params.page || 1
  const skip = (page - 1) * pageSize
  
  const total = await db.collection('dorms').count()
  const result = await query.skip(skip).limit(pageSize).get()
  
  // 处理数据，添加等级信息
  const dorms = result.data.map(dorm => {
    dorm.level = getDormLevel(dorm.currentScore || 0)
    return dorm
  })
  
  return {
    success: true,
    dorms: dorms,
    total: total.total,
    page: page,
    pageSize: pageSize,
    totalPages: Math.ceil(total.total / pageSize)
  }
}

// 获取单个宿舍详情
async function getDorm(dormId) {
  try {
    const result = await db.collection('dorms').doc(dormId).get()
    
    if (!result.data) {
      return {
        success: false,
        message: '宿舍不存在'
      }
    }
    
    // 添加宿舍等级
    const dorm = result.data
    dorm.level = getDormLevel(dorm.currentScore)
    
    // 获取最近的检查记录
    const checks = await db.collection('checks')
      .where({
        dormId: dormId
      })
      .orderBy('checkDate', 'desc')
      .limit(5)
      .get()
    
    // 获取未完成的整改任务
    const tasks = await db.collection('tasks')
      .where({
        dormId: dormId,
        status: _.in(['待整改', '已提交'])
      })
      .get()
    
    return {
      success: true,
      dorm: dorm,
      recentChecks: checks.data,
      pendingTasks: tasks.data
    }
  } catch (error) {
    return {
      success: false,
      message: '获取宿舍详情失败',
      error: error
    }
  }
}

// 批量创建宿舍
async function batchCreateDorms(dorms, openid) {
  if (!Array.isArray(dorms) || dorms.length === 0) {
    return {
      success: false,
      message: '无效的宿舍数据'
    }
  }
  
  const results = []
  const now = new Date()
  
  for (const dorm of dorms) {
    // 检查宿舍是否已存在
    const exist = await db.collection('dorms').where({
      building: dorm.building,
      roomNo: dorm.roomNo
    }).count()
    
    if (exist.total > 0) {
      results.push({
        building: dorm.building,
        roomNo: dorm.roomNo,
        success: false,
        message: '宿舍已存在'
      })
      continue
    }
    
    // 设置初始状态
    const newDorm = {
      building: dorm.building,
      roomNo: dorm.roomNo,
      members: dorm.members || [],
      monitorId: dorm.monitorId || '',
      currentScore: dorm.currentScore || 80, // 默认初始分数
      scoreHistory: [],
      images: dorm.images || [],
      medals: getInitialMedals(dorm.currentScore || 80),
      createTime: now,
      updateTime: now
    }
    
    try {
      const result = await db.collection('dorms').add({
        data: newDorm
      })
      
      results.push({
        building: dorm.building,
        roomNo: dorm.roomNo,
        success: true,
        dormId: result._id
      })
    } catch (error) {
      results.push({
        building: dorm.building,
        roomNo: dorm.roomNo,
        success: false,
        message: '创建失败',
        error: error
      })
    }
  }
  
  return {
    success: true,
    results: results,
    message: `批量创建完成，成功: ${results.filter(r => r.success).length}，失败: ${results.filter(r => !r.success).length}`
  }
}

// 重置宿舍分数
async function resetDormScore(dormId, score, openid) {
  if (!dormId) {
    return {
      success: false,
      message: '缺少宿舍ID'
    }
  }
  
  if (score === undefined || score < 0 || score > 100) {
    return {
      success: false,
      message: '无效的分数值'
    }
  }
  
  // 获取原宿舍数据
  const dormResult = await db.collection('dorms').doc(dormId).get()
  
  if (!dormResult.data) {
    return {
      success: false,
      message: '宿舍不存在'
    }
  }
  
  const dorm = dormResult.data
  
  // 更新分数
  const updateData = {
    currentScore: score,
    updateTime: new Date()
  }
  
  // 根据分数更新勋章
  updateData.medals = updateMedals(dorm.medals || [], score)
  
  // 执行更新
  await db.collection('dorms').doc(dormId).update({
    data: updateData
  })
  
  // 如果分数大于等于60，清理待整改任务
  if (score >= 60) {
    await cleanupPendingTasks(dormId, score)
  }
  
  return {
    success: true,
    message: '重置宿舍分数成功'
  }
}

// 清理待整改任务
async function cleanupPendingTasks(dormId, score) {
  const tasks = await db.collection('tasks').where({
    dormId: dormId,
    status: _.in(['待整改', '已提交'])
  }).get()
  
  if (tasks.data && tasks.data.length > 0) {
    for (const task of tasks.data) {
      await db.collection('tasks').doc(task._id).update({
        data: {
          status: '已整改',
          updateTime: new Date(),
          completedScore: score,
          feedback: {
            content: `宿舍环境已改善，当前分数: ${score}分`,
            submitTime: new Date(),
            submitterId: 'system',
            submitterName: '系统'
          }
        }
      })
    }
  }
}

// 根据分数获取宿舍等级
function getDormLevel(score) {
  if (score >= 90) return "优秀宿舍";
  if (score >= 75) return "良好宿舍";
  if (score >= 60) return "合格宿舍";
  return "不合格宿舍";
}

// 根据分数获取初始勋章
function getInitialMedals(score) {
  if (score >= 90) return ["优秀宿舍"];
  return [];
}

// 根据分数更新勋章列表
function updateMedals(currentMedals, score) {
  let medals = [...currentMedals];
  
  // 分数达到90分以上，添加"优秀宿舍"勋章
  if (score >= 90) {
    if (!medals.includes('优秀宿舍')) {
      medals.push('优秀宿舍');
    }
  } 
  // 分数低于90分，移除"优秀宿舍"勋章
  else {
    medals = medals.filter(m => m !== '优秀宿舍');
  }
  
  // 分数低于60分，清空所有勋章
  if (score < 60) {
    medals = [];
  }
  
  return medals;
} 